package dovs.peephole;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PushbackReader;

import dovs.peephole.lexer.Lexer;
import dovs.peephole.lexer.LexerException;
import dovs.peephole.node.APatternCollection;
import dovs.peephole.parser.Parser;
import dovs.peephole.parser.ParserException;

public class Loader {

	// For testing
	public static void main(String args[]) {
		try {
			load(args[0]);
		} catch (PeepholeException e) {
			if (PeepholeDriver.current_pattern != null) {
				System.out.println("Error in peephole pattern "
						+ PeepholeDriver.current_pattern.getName().getText()
						+ ":");
			} else {
				System.out.println("Error in peephole patterns:");
			}
			System.out.println(e.getMessage());
		} catch (IOException e) {
			System.out.println("I/O error:");
			System.out.println(e.getMessage());
		}
	}

	public static APatternCollection load(String filename) throws IOException {
		Parser parser = new Parser(new Lexer(new PushbackReader(
				new InputStreamReader(new FileInputStream(filename),
						"ISO-8859-1"), 4096)));
		try {
			APatternCollection patterns = parser.parse().getPatternCollection();
			patterns.apply(Prepare.aspectOf());
			return patterns;
		} catch (LexerException e) {
			throw new PeepholeException("Lexer error: " + e.getMessage());
		} catch (ParserException e) {
			throw new PeepholeException("Parser error: " + e.getMessage());
		}
	}

}
